package com.jjty.dataGenerator.bg.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jjty.dataGenerator.bg.entity.ScClassStudentRequestByXZN;
import com.jjty.dataGenerator.bg.entity.ScStudentInfoRequest;
import com.jjty.dataGenerator.bg.entity.SchoolInfo;
import com.jjty.dataGenerator.bg.entity.StudentInfo;
import com.jjty.dataGenerator.bg.mapper.SchoolMapper;
import com.jjty.dataGenerator.bg.service.StudentInfoService;
import com.jjty.dataGenerator.common.ApiResult;
import com.jjty.dataGenerator.common.PageParamReader;
import com.jjty.dataGenerator.utils.ExcelReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author leikk
 * @since 2025-03-19
 */
@RestController
@RequestMapping("/bg/student")
public class StudentInfoController {

    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private SchoolMapper schoolInfoMapper;

    @RequestMapping("/importByExcel")
    public ApiResult importStudents(@RequestParam("file") MultipartFile file) {
        try {
            File tempFile = File.createTempFile("temp", ".xlsx");
            file.transferTo(tempFile);
            Map<String, Object> excelData = ExcelReader.readExcel(tempFile);
            List<String> header = (List<String>) excelData.get("header");
            List<List<String>> data = (List<List<String>>) excelData.get("data");

            // 记录列名对应的索引
            Map<String, Integer> columnIndexMap = new HashMap<>();
            for (int i = 0; i < header.size(); i++) {
                columnIndexMap.put(header.get(i), i);
            }

            List<StudentInfo> students = new ArrayList<>();
            for (List<String> row : data) {
                StudentInfo student = new StudentInfo();
                student.setPhoneNumber(getValueByColumnName(columnIndexMap, row, "phone_number"));
                student.setStudentId(getValueByColumnName(columnIndexMap, row, "student_id"));
                String ecCode = getValueByColumnName(columnIndexMap, row, "ec_code");
                student.setEcCode(ecCode);
                student.setStudentName(getValueByColumnName(columnIndexMap, row, "student_name"));
                student.setParentName(getValueByColumnName(columnIndexMap, row, "parent_name"));
                student.setStudentNumber(getValueByColumnName(columnIndexMap, row, "student_number"));
                // 检查 ec_code 是否在 school_info 表中存在对应的 ecid
                QueryWrapper<SchoolInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("ecid", ecCode);
                SchoolInfo schoolInfo = schoolInfoMapper.selectOne(queryWrapper);
                if (schoolInfo == null) {
                    return ApiResult.doFailure("导入失败，ec_code " + ecCode + " 在 school_info 表中无对应记录");
                }
                students.add(student);
            }

            boolean result = studentInfoService.saveBatch(students);
            if (result) {
                return ApiResult.doSuccess("导入学生数据成功");
            } else {
                return ApiResult.doFailure("导入学生数据失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResult.doFailure("导入学生数据失败：" + e.getMessage());
        }
    }

    private String getValueByColumnName(Map<String, Integer> columnIndexMap, List<String> row, String columnName) {
        Integer index = columnIndexMap.get(columnName);
        return index != null && index < row.size() ? row.get(index) : null;
    }

    @RequestMapping("/queryStudentList")
    public ApiResult pagingQuery(HttpServletRequest request, StudentInfo param, String keyword) {
        Page page = PageParamReader.read(request);
        page = studentInfoService.getStudentPage(page,param,keyword);
        return ApiResult.querySuccess(page);
    }

    @RequestMapping("/saveStudentInfo")
    public ApiResult saveStudentInfo(ScStudentInfoRequest scStudentInfoRequest) {
        studentInfoService.saveStudentInfo(scStudentInfoRequest);
        return ApiResult.doSuccess();
    }
    @RequestMapping("/saveAllStudent")
    public ApiResult saveAllStudent(ScClassStudentRequestByXZN scClassStudentRequestByXZN) {
        studentInfoService.saveAllStudent(scClassStudentRequestByXZN);
        return ApiResult.doSuccess();
    }
}

